package com.cw.lang.common.framework.inteceptor;

import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolation;
import javax.validation.Validator;

import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.web.servlet.HandlerInterceptor;

import com.cw.base.common.model.constants.RestConstant;
import com.cw.base.common.model.dto.base.BaseRequest;
import com.cw.base.common.model.util.AppParamUtil;
import com.cw.lang.common.constants.SymbolConstants;
import com.cw.lang.common.exception.CheckException;
import com.cw.lang.common.framework.enums.EnumRpcError;
import com.cw.lang.common.utils.CollectionUtil;
import com.google.common.collect.Sets;

import lombok.Getter;
import lombok.Setter;

/**
 * @author chenw
 * @version $$Id: LocalMvcHandlerInterceptor.java, v 0.1 2018/10/22 6:15 PM chenw Exp $$
 */
@Getter
@Setter
@Order(Ordered.HIGHEST_PRECEDENCE + 1500)
public class RequestValidatorMvcHandlerInterceptor implements HandlerInterceptor {

    private Validator validator;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        if (!request.getRequestURI()
            .startsWith(RestConstant.BASE_URL_PREFIX)) {
            return true;
        }
        Set<ConstraintViolation<Object>> constraintViolations = Sets.newHashSet();

        if (CollectionUtil.isEmpty(constraintViolations)) {
            // 校验BaseRequest，由于BaseRequest
            BaseRequest baseRequest = AppParamUtil.getBaseRequest();
            constraintViolations.addAll(validator.validate(baseRequest));
        }

        // 校验BaseUserRequest，由于BaseUserRequest可为null，所以不强制校验
        if (CollectionUtil.isEmpty(constraintViolations) && AppParamUtil.getBaseUserRequest() != null) {
            constraintViolations.addAll(validator.validate(AppParamUtil.getBaseUserRequest()));
        }

        //noinspection Duplicates
        if (CollectionUtil.isNotEmpty(constraintViolations)) {
            StringBuilder sb = new StringBuilder();
            // 仅展示错误message
            constraintViolations.forEach(input -> sb.append(input.getMessage())
                .append(SymbolConstants.COMMA));
            throw new CheckException(EnumRpcError.VALIDATOR_ERROR.getCode(),
                EnumRpcError.VALIDATOR_ERROR.getDescription(), sb.substring(0, sb.length() - 1));
        }
        return true;
    }

}
